package buco.core.api;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.simple.*;

public class ExportCompositionCommand extends Command<Void, File> {

	@Override
	public File execute() throws Exception {
		List<Integer> files = new ArrayList<Integer>(); 
		for(Bundle bundle : composition.getBundles()) {
			files.add(bundle.getFileID()); 
		}		
		return fileManager.createExport(files, exportComposition());
	}
	
	@SuppressWarnings("unchecked")
	private String exportComposition() {
		JSONObject obj = new JSONObject();
		JSONArray bundlesArr = new JSONArray(); 
		JSONArray wiresArr = new JSONArray();
		obj.put("bundles", bundlesArr); 
		obj.put("wires", wiresArr);
		
		for(Bundle bundle : composition.getBundles()) {
			int id = bundle.getBundleID(); 
			int top = 0; 
			
			if(bundle.getCustomProperty("top") != null) { 
				top = (int) bundle.getCustomProperty("top");
			}
			
			int left = 0; 
			if(bundle.getCustomProperty("left") != null) { 
				left = (int) bundle.getCustomProperty("left");
			}
			
			File jarFile = fileManager.getFileByID(bundle.getFileID()); 
			JSONObject bundleObj = new JSONObject(); 
			bundleObj.put("id", id);
			bundleObj.put("file", jarFile.getName());
			bundleObj.put("top", top);
			bundleObj.put("left", left);
			bundlesArr.add(bundleObj); 						
		}
		
		for(BundleWire wire : composition.getWires()) {
			int from = wire.getFrom().getBundleID();
			int to = wire.getTo().getBundleID();			
			boolean active = wire.isWireActive(); 
			JSONObject wireObj = new JSONObject(); 
			wireObj.put("from", from);
			wireObj.put("to", to); 
			wireObj.put("active", active);
			wiresArr.add(wireObj); 
		}
		
		return obj.toJSONString(); 
	}

	@Override
	public boolean canUndo() { 
		return false;
	}

}
